package io.renren.modules.training.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.modules.combat.entity.TFightInformationEntity;
import io.renren.modules.generator.entity.TTrainingEntity;
import io.renren.modules.generator.entity.TTrainingScoreEntity;
import io.renren.modules.generator.entity.vo.TTrainingScoreVo;
import io.renren.modules.generator.service.TTrainingScoreService;
import io.renren.modules.oss.cloud.OSSFactory;
import io.renren.modules.oss.entity.SysOssEntity;
import io.renren.modules.test.FileUtil;
import io.renren.modules.training.entity.vo.ResumeInfoVo;
import io.renren.modules.training.service.TrainingManageService;
import io.renren.modules.training.util.Base64Utils;
import io.renren.modules.training.util.PoiUtil;
import io.renren.modules.user.entity.TPeopleEntity;
import io.renren.modules.user.entity.TPeopleResumeEntity;
import io.renren.modules.user.service.TPeopleService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/training")
public class TrainingManageController {
    @Resource
    private TrainingManageService trainingManageService;
    @Resource
    private TTrainingScoreService tTrainingScoreService;
    @Resource
    private ThreadPoolTaskExecutor executor;
    @Resource
    private TPeopleService tPeopleService;

    /**
     * 成绩导入
     */
    @RequestMapping("/scoreImport")
    @ResponseBody
    public R scoreImport(@RequestParam("file") MultipartFile file,@RequestParam("trainingId")Integer trainingId, @RequestParam("trainingCheckId")Integer trainingCheckId) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        String fileName=file.getOriginalFilename();
        if((!fileName.endsWith("xls")) && (!fileName.endsWith("xlxs"))){
            return R.error("文件类型有误");
        }

        InputStream inputStream=file.getInputStream();

        Workbook workbook = PoiUtil.getWorkbookByFile(inputStream);
        Map<String,Object> map=trainingManageService.getTrainingScoreInfo(workbook,trainingId,trainingCheckId);
        if(map==null||map.isEmpty()){
            return R.error();
        }
        Boolean flag=(Boolean) map.get("isValid");
        String msg=(String)map.get("message");
        if(!flag){
            return R.error(msg);
        }
        List<TTrainingScoreVo> list=(List<TTrainingScoreVo>)map.get("list");
        if(CollectionUtils.isNotEmpty(list)){
            Boolean flag2=tTrainingScoreService.DrTTrainingScore(list);
            if(!flag2){
                return R.error("导入失败");
            }

            executor.execute(() -> {
                for (TTrainingScoreVo tTrainingScoreVo : list) {
                    TTrainingScoreEntity tTrainingScoreEntity=new TTrainingScoreEntity();
                    tTrainingScoreEntity.setTrainingId(tTrainingScoreVo.getTrainingId());
                    tTrainingScoreEntity.setTrainingCheckId(tTrainingScoreVo.getTrainingCheckId());
                    List<TTrainingScoreEntity> scoreEntityList=tTrainingScoreService.automaticScoring(tTrainingScoreEntity);
                    String scoreEntityListStr=JSONObject.toJSONString(scoreEntityList);
                    List<TTrainingScoreEntity> scoreEntityList2=JSONObject.parseObject(scoreEntityListStr,new TypeReference<List<TTrainingScoreEntity>>(){});
                    for (TTrainingScoreEntity tTrainingScoreEntity1:scoreEntityList2) {
                        tTrainingScoreService.updateMarkAndjudgeSingle(tTrainingScoreEntity1);
                    }
//                    tTrainingScoreService.updateMarkAndjudge(scoreEntityList);
                }
            });

        }
        return R.ok();
    }

    /**
     * 成绩导出
     */
    @RequestMapping("/scoreExport")
    @ResponseBody
    public ResponseEntity<byte[]> scoreExport(Integer trainingId,Integer checkCount ) throws Exception {

        List<TTrainingScoreEntity> scoreEntityList=tTrainingScoreService.selectByTrainingIdAndChenkCount(trainingId,checkCount);
        List<TTrainingScoreEntity> scoreEntityList2=JSONObject.parseObject(JSONObject.toJSONString(scoreEntityList),new TypeReference<List<TTrainingScoreEntity>>(){});

        String tempFilePath = getTempFilePath();
//        String path=templatePath.substring(0,templatePath.lastIndexOf(File.separator)+1);

        String fileName="成绩表.xls";
        File file = new File(tempFilePath+fileName);
        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream os = new FileOutputStream(file);

        Boolean flag=trainingManageService.createExcel(os,scoreEntityList2);

        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        fileName=new String(fileName.getBytes("UTF-8"),"iso-8859-1");
        //通知浏览器以attachment（下载方式）
        headers.setContentDispositionFormData("attachment", fileName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);


    }


    /**
     * 单位指标成绩对比分析
     */
    @RequestMapping("/getScoreList")
    @ResponseBody
    public R getScoreList(Integer trainingId,Integer checkCount ){
        if(trainingId==null ||checkCount==null){
            return R.error("参数不能为空");
        }
        List<TTrainingScoreEntity> scoreEntityList=tTrainingScoreService.selectByTrainingIdAndChenkCount(trainingId,checkCount);
        List<TTrainingScoreEntity> scoreEntityList2=JSONObject.parseObject(JSONObject.toJSONString(scoreEntityList),new TypeReference<List<TTrainingScoreEntity>>(){});
        List<List<String>> list=trainingManageService.getTraingScoreData(scoreEntityList2);
        return R.ok().put("data",list);
    }

    /**
     * 单位指标成绩对比分析
     */
    @RequestMapping("/getPeople")
    @ResponseBody
    public R getScoreList(Integer id ){
        if(id==null ){
            return R.error("参数不能为空");
        }
        Map<String,Object> map=tTrainingScoreService.selectPeople(id);
        return R.ok().put("data",map);
    }




    private String getTempFilePath(){
        String dir="";
        try {

            dir = new File(ResourceUtils.getURL("classpath:").getPath()).getParentFile().getParentFile().getParent().substring(5);
            System.out.println("dir"+dir);
//        org.springframework.core.io.Resource resource = new ClassPathResource("");
//            dir=resource.getFile().getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        String proFilePath = System.getProperty("user.dir");
//        String dir= request.getSession().getServletContext().getRealPath(File.separator);
        dir=dir+File.separator+"static"+File.separator+"tempFilePath"+File.separator;
        return dir;
    }

    /**
     * 简历导出
     */
    @RequestMapping("/resumeExport")
    @ResponseBody
    public void  resumeExport(ResumeInfoVo resumeInfoVo1,HttpServletResponse response) throws Exception {

        /*测试代码开始*/
        String templatePath2 = getTempFilePath();
        /*测试代码结束*/

        Integer peopleId=resumeInfoVo1.getPeopleId();

        TPeopleEntity tPeopleEntity = tPeopleService.getById(peopleId);
        Integer peopleType=0;
        if(tPeopleEntity!=null){
            peopleType=tPeopleEntity.getPeopleType();
        }
        if(peopleType==0){
            replace(templatePath2+"xiaofangyuan.ftl");
        }else if(peopleType==1){
            replace(templatePath2+"zhuanzhi.ftl");
        }else if(peopleType==2) {
            replace(templatePath2+"ganbu.ftl");
        }else {
            replace(templatePath2+"xiaofangyuan.ftl");
        }

        //查询工作经理
        List<TPeopleResumeEntity> peopleResumeList = tPeopleService.findPeopleResume(peopleId);
        //查询战斗经历
        List<TFightInformationEntity> fightList =tPeopleService.findFight(peopleId);
        //训练经历
        List<TTrainingEntity> peopleTTraining = tPeopleService.findPeopleTTraining(peopleId);


        resumeInfoVo1.setImageStr(image2Base64(tPeopleEntity.getPicture()));
        resumeInfoVo1.setName(tPeopleEntity.getName());
        resumeInfoVo1.setIdNo(tPeopleEntity.getIdcard());
//        resumeInfoVo1.setNation(tPeopleEntity.getEthnic());
        resumeInfoVo1.setNativePlace(tPeopleEntity.getBround());
        resumeInfoVo1.setBloodType(tPeopleEntity.getBlood());
        resumeInfoVo1.setGraduateSchool(tPeopleEntity.getSchool());
        if(tPeopleEntity.getEducationTime()!=null){
            resumeInfoVo1.setGradeTime(new SimpleDateFormat("yyyy-MM-dd").format(tPeopleEntity.getEducationTime()));
        }
        resumeInfoVo1.setEmail(tPeopleEntity.getEmail());
        resumeInfoVo1.setMajor(tPeopleEntity.getMajor());
        if(peopleType==0){
            resumeInfoVo1.setPersonnelType("消防员");
        }else if(peopleType==1){
            resumeInfoVo1.setPersonnelType("专职消防员");
        }else if(peopleType==2){
            resumeInfoVo1.setPersonnelType("干部");
        }

        resumeInfoVo1.setHistoryName(tPeopleEntity.getOldName());
        if(tPeopleEntity.getHight()!=null){
            resumeInfoVo1.setHeight(tPeopleEntity.getHight().toString());
        }
//        resumeInfoVo1.setEducation(tPeopleEntity.getEducation());
        resumeInfoVo1.setPhone(tPeopleEntity.getCallPhone());
        resumeInfoVo1.setFireNo(tPeopleEntity.getFireIdcard());
        if(tPeopleEntity.getDutyPostTime()!=null){
            resumeInfoVo1.setPostTime(new SimpleDateFormat("yyyy-MM-dd").format(tPeopleEntity.getDutyPostTime()));
        }
        if(tPeopleEntity.getAdministrationTime()!=null){
            resumeInfoVo1.setAdminPostTime(new SimpleDateFormat("yyyy-MM-dd").format(tPeopleEntity.getAdministrationTime()));
        }
        String contractType=tPeopleEntity.getContractType();
        if("0".equals(contractType)){
            resumeInfoVo1.setContractYear("无固定期限");
        }else if("1".equals(contractType)){
            resumeInfoVo1.setContractYear("五年");
        }else if("2".equals(contractType)){
            resumeInfoVo1.setContractYear("三年");
        }
        resumeInfoVo1.setCurrentYear(tPeopleEntity.getContractYear());
        if(tPeopleEntity.getTitleTime()!=null){
            resumeInfoVo1.setRankTime(new SimpleDateFormat("yyyy-MM-dd").format(tPeopleEntity.getTitleTime()));
        }
        if(tPeopleEntity.getFireClassTime()!=null){
            resumeInfoVo1.setTechnicalTime(new SimpleDateFormat("yyyy-MM-dd").format(tPeopleEntity.getFireClassTime()));
        }
        String tecClass=tPeopleEntity.getTecClass();
        if("0".equals(tecClass)){
            resumeInfoVo1.setTechnicalGrade("技术员");
        }else if("1".equals(tecClass)){
            resumeInfoVo1.setTechnicalGrade("助理工程师");
        }else if("2".equals(tecClass)){
            resumeInfoVo1.setTechnicalGrade("工程师");
        }else if("3".equals(tecClass)){
            resumeInfoVo1.setTechnicalGrade("高级工程师");
        }
        if(tPeopleEntity.getTecClassTime()!=null){
            resumeInfoVo1.setGradeTime(new SimpleDateFormat("yyyy-MM-dd").format(tPeopleEntity.getTecClassTime()));
        }
        String political=tPeopleEntity.getPolitical();
        if("0".equals(political)){
            resumeInfoVo1.setPoliticalDuty("群众");
        }else if("1".equals(political)){
            resumeInfoVo1.setPoliticalDuty("团员");
        }else if("2".equals(political)){
            resumeInfoVo1.setPoliticalDuty("预备党员");
        }else if("3".equals(political)){
            resumeInfoVo1.setPoliticalDuty("党员");
        }
        if(tPeopleEntity.getPoliTime()!=null){
            resumeInfoVo1.setJoinPartyTime(new SimpleDateFormat("yyyy-MM-dd").format(tPeopleEntity.getPoliTime()));
        }
        String marry=tPeopleEntity.getMarry();
        if("0".equals(marry)){
            resumeInfoVo1.setMaritalStatus("未婚");
        }else if("1".equals(marry)){
            resumeInfoVo1.setMaritalStatus("已婚");
            resumeInfoVo1.setMate(tPeopleEntity.getSpouse());
            resumeInfoVo1.setFertilitySituation(tPeopleEntity.getKids());
        }else if("2".equals(marry)){
            resumeInfoVo1.setMaritalStatus("离异");
            resumeInfoVo1.setFertilitySituation(tPeopleEntity.getKids());
        }
        if(tPeopleEntity.getMarryTime()!=null){
            resumeInfoVo1.setMaritalTime(new SimpleDateFormat("yyyy-MM-dd").format(tPeopleEntity.getMarryTime()));
        }
        resumeInfoVo1.setAddress(tPeopleEntity.getAddress());
        resumeInfoVo1.setFileNumber(tPeopleEntity.getFileNumber());
        resumeInfoVo1.setSpeciality(tPeopleEntity.getStrength());
        resumeInfoVo1.setRemark(tPeopleEntity.getInstructions());

        resumeInfoVo1.setBirthDay(resumeInfoVo1.getIdNo().substring(6,10)+"-"+resumeInfoVo1.getIdNo().substring(10,12)+"-"+resumeInfoVo1.getIdNo().substring(12,14));
        if(StringUtils.isNotBlank(resumeInfoVo1.getIdNo())){
            Integer sexSign=Integer.parseInt(resumeInfoVo1.getIdNo().substring(16,17));
            if(sexSign%2==1){
                resumeInfoVo1.setSex("男");
            }else {
                resumeInfoVo1.setSex("女");
            }
        }
        Map<String,Object> dataMap = new HashMap<String, Object>();
        //编号
        dataMap.put("name",resumeInfoVo1.getName()==null?"":resumeInfoVo1.getName());
        dataMap.put("historyName",resumeInfoVo1.getHistoryName()==null?"":resumeInfoVo1.getHistoryName());
        dataMap.put("idNo",resumeInfoVo1.getIdNo()==null?"":resumeInfoVo1.getIdNo());
        dataMap.put("sex", resumeInfoVo1.getSex()==null?"":resumeInfoVo1.getSex());
        dataMap.put("birthDay", resumeInfoVo1.getBirthDay()==null?"":resumeInfoVo1.getBirthDay());
        dataMap.put("height",resumeInfoVo1.getHeight()==null?"":resumeInfoVo1.getHeight());
        dataMap.put("imageStr", resumeInfoVo1.getImageStr()==null?"":resumeInfoVo1.getImageStr());
        dataMap.put("education", resumeInfoVo1.getEducation()==null?"":resumeInfoVo1.getEducation());
        dataMap.put("phone", resumeInfoVo1.getPhone()==null?"":resumeInfoVo1.getPhone());
        dataMap.put("fireNo", resumeInfoVo1.getFireNo()==null?"":resumeInfoVo1.getFireNo());
        dataMap.put("nation", resumeInfoVo1.getNation()==null?"":resumeInfoVo1.getNation());
        dataMap.put("nativePlace", resumeInfoVo1.getNativePlace()==null?"":resumeInfoVo1.getNativePlace());
        dataMap.put("bloodType", resumeInfoVo1.getBloodType()==null?"":resumeInfoVo1.getBloodType());
        dataMap.put("graduateSchool", resumeInfoVo1.getGraduateSchool()==null?"":resumeInfoVo1.getGraduateSchool());
        dataMap.put("graduateTime", resumeInfoVo1.getRaduateTime()==null?"":resumeInfoVo1.getRaduateTime());
        dataMap.put("email", resumeInfoVo1.getEmail()==null?"":resumeInfoVo1.getEmail());
        dataMap.put("major", resumeInfoVo1.getMajor()==null?"":resumeInfoVo1.getMajor());
        dataMap.put("personnelType", resumeInfoVo1.getPersonnelType()==null?"":resumeInfoVo1.getPersonnelType());
        dataMap.put("detachment", resumeInfoVo1.getDetachment()==null?"":resumeInfoVo1.getDetachment());
        dataMap.put("squadron", resumeInfoVo1.getSquadron()==null?"":resumeInfoVo1.getSquadron());
        dataMap.put("className", resumeInfoVo1.getClassName()==null?"":resumeInfoVo1.getClassName());
        dataMap.put("recruitPlace", resumeInfoVo1.getRecruitPlace()==null?"":resumeInfoVo1.getRecruitPlace());
        dataMap.put("post", resumeInfoVo1.getPost()==null?"":resumeInfoVo1.getPost());
        dataMap.put("postTime", resumeInfoVo1.getPostTime()==null?"":resumeInfoVo1.getPostTime());
        dataMap.put("adminPost", resumeInfoVo1.getAdminPost()==null?"":resumeInfoVo1.getAdminPost());
        dataMap.put("adminPostTime", resumeInfoVo1.getAdminPostTime()==null?"":resumeInfoVo1.getAdminPostTime());
        dataMap.put("contractYear", resumeInfoVo1.getContractYear()==null?"":resumeInfoVo1.getContractYear());
        dataMap.put("militaryRank", resumeInfoVo1.getMilitaryRank()==null?"":resumeInfoVo1.getMilitaryRank());
        dataMap.put("currentYear", resumeInfoVo1.getCurrentYear()==null?"":resumeInfoVo1.getCurrentYear());
        dataMap.put("rankTime", resumeInfoVo1.getRankTime()==null?"":resumeInfoVo1.getRankTime());
        dataMap.put("technicalPost", resumeInfoVo1.getTechnicalPost()==null?"":resumeInfoVo1.getTechnicalPost());
        dataMap.put("technicalTime", resumeInfoVo1.getTechnicalTime()==null?"":resumeInfoVo1.getTechnicalTime());
        dataMap.put("technicalGrade", resumeInfoVo1.getTechnicalGrade()==null?"":resumeInfoVo1.getTechnicalGrade());
        dataMap.put("gradeTime", resumeInfoVo1.getGradeTime()==null?"":resumeInfoVo1.getGradeTime());
        dataMap.put("politicalDuty", resumeInfoVo1.getPoliticalDuty()==null?"":resumeInfoVo1.getPoliticalDuty());
        dataMap.put("joinPartyTime", resumeInfoVo1.getJoinPartyTime()==null?"":resumeInfoVo1.getJoinPartyTime());
        dataMap.put("jobTime", resumeInfoVo1.getJobTime()==null?"":resumeInfoVo1.getJobTime());
        dataMap.put("hisJobTime", resumeInfoVo1.getHisJobTime()==null?"":resumeInfoVo1.getHisJobTime());
        dataMap.put("unitJobTime", resumeInfoVo1.getUnitJobTime()==null?"":resumeInfoVo1.getUnitJobTime());
        dataMap.put("totalJobTime", resumeInfoVo1.getTotalJobTime()==null?"":resumeInfoVo1.getTotalJobTime());
        dataMap.put("nowRegister", resumeInfoVo1.getNowRegister()==null?"":resumeInfoVo1.getNowRegister());
        dataMap.put("registerType", resumeInfoVo1.getRegisterType()==null?"":resumeInfoVo1.getRegisterType());
        dataMap.put("hisRegister", resumeInfoVo1.getHisRegister()==null?"":resumeInfoVo1.getHisRegister());
        dataMap.put("hisRegisterType", resumeInfoVo1.getHisRegisterType()==null?"":resumeInfoVo1.getHisRegisterType());
        dataMap.put("family", resumeInfoVo1.getFamily()==null?"":resumeInfoVo1.getFamily());
        dataMap.put("isSingleChild", resumeInfoVo1.getIsSingleChild()==null?"":resumeInfoVo1.getIsSingleChild());
        dataMap.put("isUniversitySoldiers", resumeInfoVo1.getIsUniversitySoldiers()==null?"":resumeInfoVo1.getIsUniversitySoldiers());
        dataMap.put("isCadreChildren", resumeInfoVo1.getIsCadreChildren()==null?"":resumeInfoVo1.getIsCadreChildren());
        dataMap.put("maritalStatus", resumeInfoVo1.getMaritalStatus()==null?"":resumeInfoVo1.getMaritalStatus());
        dataMap.put("maritalTime", resumeInfoVo1.getMaritalTime()==null?"":resumeInfoVo1.getMaritalTime());
        dataMap.put("mate", resumeInfoVo1.getMate()==null?"":resumeInfoVo1.getMate());
        dataMap.put("fertilitySituation", resumeInfoVo1.getFertilitySituation()==null?"":resumeInfoVo1.getFertilitySituation());
        dataMap.put("address", resumeInfoVo1.getAddress()==null?"":resumeInfoVo1.getAddress());
        dataMap.put("fileNumber", resumeInfoVo1.getFileNumber()==null?"":resumeInfoVo1.getFileNumber());
        dataMap.put("speciality", resumeInfoVo1.getSpeciality()==null?"":resumeInfoVo1.getSpeciality());
        dataMap.put("remark", resumeInfoVo1.getRemark()==null?"":resumeInfoVo1.getRemark());
        StringBuffer workHistory=new StringBuffer();
        StringBuffer trainHistory=new StringBuffer();
        StringBuffer fightHistory=new StringBuffer();
        if(CollectionUtils.isNotEmpty(peopleResumeList)){
            for (TPeopleResumeEntity entity:peopleResumeList) {
                workHistory.append(entity.getStartTime()==null ?"":new SimpleDateFormat("yyyy.MM.dd").format(entity.getStartTime())+"-");
                workHistory.append(entity.getEndTime()==null ?"":new SimpleDateFormat("yyyy.MM.dd").format(entity.getEndTime()));
                workHistory.append(" ");
                workHistory.append(entity.getOrgazation()+"任");
                workHistory.append(entity.getTitle());
                workHistory.append("<w:br></w:br>"+"   ");
            }
        }
        if(CollectionUtils.isNotEmpty(fightList)){
            for (TFightInformationEntity entity:fightList) {
                fightHistory.append(entity.getTime()==null ?"":new SimpleDateFormat("yyyy.MM.dd").format(entity.getTime())+"-");
                fightHistory.append(entity.getOffTime()==null ?"":new SimpleDateFormat("yyyy.MM.dd").format(entity.getOffTime()));
                fightHistory.append(" 在"+entity.getAddress()+"参加");
                fightHistory.append(entity.getStuation());
                workHistory.append("<w:br></w:br>"+"   ");
            }
        }
        if(CollectionUtils.isNotEmpty(peopleTTraining)){
            for (TTrainingEntity entity:peopleTTraining) {
                trainHistory.append(entity.getStartTime()==null ?"":new SimpleDateFormat("yyyy.MM.dd").format(entity.getEndTime())+"-");
                trainHistory.append(entity.getEndTime()==null ?"":new SimpleDateFormat("yyyy.MM.dd").format(entity.getEndTime()));
                trainHistory.append(" 参加");
                trainHistory.append(entity.getStuation());
                workHistory.append("<w:br></w:br>"+"   ");
            }
        }

        dataMap.put("workHistory", workHistory.toString());
        dataMap.put("trainHistory", trainHistory.toString());
        dataMap.put("fightHistory", fightHistory.toString());

        //Configuration 用于读取ftl文件
        Configuration configuration = new Configuration(new Version("2.3.0"));
        configuration.setDefaultEncoding("utf-8");

        String templatePath = getTempFilePath();
        configuration.setDirectoryForTemplateLoading(new File(templatePath));

        //输出文档路径及名称
        String fileName="简历.doc";
        File outFile = new File(templatePath+fileName);

        //以utf-8的编码读取ftl文件
        Template template=null;
        if(peopleType==0){
            template = configuration.getTemplate("xiaofangyuan.ftl", "utf-8");
        }else if(peopleType==1){
            template = configuration.getTemplate("zhuanzhi.ftl", "utf-8");
        }else if(peopleType==2){
            template = configuration.getTemplate("ganbu.ftl", "utf-8");
        }else {
            template = configuration.getTemplate("xiaofangyuan.ftl", "utf-8");
        }
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
        template.process(dataMap, out);
        out.close();


//        HttpHeaders headers = new HttpHeaders();
//        //下载显示的文件名，解决中文名称乱码问题
//        fileName=new String(fileName.getBytes("UTF-8"),"iso-8859-1");
//        //通知浏览器以attachment（下载方式）
//        headers.setContentDispositionFormData("attachment", fileName);
//        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//        Map<String,Object> map=new HashMap<>();
//        map.put("data",new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(outFile),
//                headers, HttpStatus.CREATED));
//        return R.ok(map);


        try {
            InputStream bis = new BufferedInputStream(new FileInputStream(new File(templatePath+fileName)));
            fileName = URLEncoder.encode(fileName,"UTF-8");
            //设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            ServletOutputStream outputStream=response.getOutputStream();
            IOUtils.copy(bis,outputStream);
            outputStream.close();
            bis.close();
//            BufferedOutputStream out2 = new BufferedOutputStream(response.getOutputStream());
//            int len = 0;
//            while((len = bis.read()) != -1){
//                out2.write(len);
//                out2.flush();
//            }
//            out2.close();
        } catch (Exception e) {
        }
//        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(outFile),
//                headers, HttpStatus.CREATED);
    }



    public  String read(String path) {
        File file = new File(path);
        StringBuffer res = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            while ((line = reader.readLine()) != null) {
                res.append(line + "\n");
            }
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res.toString();
    }

    public  boolean write(String cont, File dist) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(dist));
            writer.write(cont);
            writer.flush();
            writer.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public  void replace(String path) {
        File src = new File(path);
        String cont = read(path);
        //对得到的内容进行处理
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:proofErr w:type=\"spellStart\"/><w:r><w:rPr><w:rFonts w:hint=\"eastAsia\"/></w:rPr><w:t>", "\\$\\{");
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:r w:rsidR=\"0053250B\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\"/><w:kern w:val=\"0\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>", "\\$\\{");
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:proofErr w:type=\"spellStart\"/><w:r w:rsidR=\"0053250B\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"32\"/></w:rPr><w:t>", "\\$\\{");
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:r w:rsidR=\"00472FAC\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\"/><w:kern w:val=\"0\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>", "\\$\\{");
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:r w:rsidR=\"006C72C3\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:kern w:val=\"0\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>", "\\$\\{");
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:r w:rsidR=\"00075165\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>", "\\$\\{");
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:proofErr w:type=\"spellStart\"/><w:r w:rsidR=\"007001C3\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"32\"/></w:rPr><w:t>", "\\$\\{");
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:proofErr w:type=\"spellStart\"/><w:r w:rsidR=\"007001C3\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>", "\\$\\{");
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:proofErr w:type=\"spellStart\"/><w:r w:rsidR=\"006A2364\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>", "\\$\\{");
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:proofErr w:type=\"spellStart\"/><w:r><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>", "\\$\\{");
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:proofErr w:type=\"spellStart\"/><w:r w:rsidR=\"00075165\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>", "\\$\\{");
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:proofErr w:type=\"spellStart\"/><w:r w:rsidR=\"00C91F84\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>", "\\$\\{");
        cont = cont.replaceAll("\\$\\{</w:t></w:r><w:proofErr w:type=\"spellStart\"/><w:r w:rsidR=\"007503BF\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>", "\\$\\{");


        cont = cont.replaceAll("</w:t></w:r><w:proofErr w:type=\"spellEnd\"/><w:r><w:rPr><w:rFonts w:hint=\"eastAsia\"/></w:rPr><w:t>\\}", "\\}");
        cont = cont.replaceAll("</w:t></w:r><w:r w:rsidR=\"0053250B\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:kern w:val=\"0\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>\\}", "\\}");
        cont = cont.replaceAll("</w:t></w:r><w:proofErr w:type=\"spellEnd\"/><w:r w:rsidR=\"0053250B\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"32\"/></w:rPr><w:t>\\}", "\\}");
        cont = cont.replaceAll("</w:t></w:r><w:r><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>\\}", "\\}");
        cont = cont.replaceAll("</w:t></w:r><w:proofErr w:type=\"spellEnd\"/><w:r w:rsidR=\"007001C3\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"32\"/></w:rPr><w:t>\\}", "\\}");
        cont = cont.replaceAll("</w:t></w:r><w:proofErr w:type=\"spellEnd\"/><w:r w:rsidR=\"007001C3\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>\\}", "\\}");
        cont = cont.replaceAll("</w:t></w:r><w:proofErr w:type=\"spellEnd\"/><w:r w:rsidR=\"006A2364\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>\\}", "\\}");
        cont = cont.replaceAll("</w:t></w:r><w:proofErr w:type=\"spellEnd\"/><w:r><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>\\}", "\\}");
        cont = cont.replaceAll("</w:t></w:r><w:proofErr w:type=\"spellEnd\"/><w:r w:rsidR=\"00C91F84\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>\\}", "\\}");
        cont = cont.replaceAll("</w:t></w:r><w:proofErr w:type=\"spellEnd\"/><w:r w:rsidR=\"007503BF\"><w:rPr><w:rFonts w:ascii=\"宋体\" w:eastAsia=\"宋体\" w:hAnsi=\"宋体\" w:hint=\"eastAsia\"/><w:sz w:val=\"28\"/><w:szCs w:val=\"28\"/></w:rPr><w:t>\\}", "\\}");

        //更新源文件
        write(cont, src);
    }


    /**
     * 通过图片的url获取图片的base64字符串
     * @param imgUrl    图片url
     * @return    返回图片base64的字符串
     */
    public  String image2Base64(String imgUrl) {

        URL url = null;

        InputStream is = null;

        ByteArrayOutputStream outStream = null;

        HttpURLConnection httpUrl = null;

        try{

            url = new URL(imgUrl);

            httpUrl = (HttpURLConnection) url.openConnection();

            httpUrl.connect();

            httpUrl.getInputStream();

            is = httpUrl.getInputStream();



            outStream = new ByteArrayOutputStream();

            //创建一个Buffer字符串

            byte[] buffer = new byte[1024];

            //每次读取的字符串长度，如果为-1，代表全部读取完毕

            int len = 0;

            //使用一个输入流从buffer里把数据读取出来

            while( (len=is.read(buffer)) != -1 ){

                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度

                outStream.write(buffer, 0, len);

            }

            // 对字节数组Base64编码

            return encode(outStream.toByteArray());

        }catch (Exception e) {

            e.printStackTrace();

        }

        finally{

            if(is != null)

            {

                try {

                    is.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if(outStream != null)

            {

                try {

                    outStream.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if(httpUrl != null)

            {

                httpUrl.disconnect();

            }

        }

        return imgUrl;

    }

    /**
     30      * 图片转字符串
     31      * @param image
     32      * @return
     33      */
    public String encode(byte[] image){

        String encodeStr="";
        try {
            encodeStr=Base64Utils.encode(image);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return replaceEnter(encodeStr);
    }


    public  String replaceEnter(String str){
        String reg ="[\n-\r]";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }




}
